package jianzhiOffer;

public class Num67 {
    public int strToInt(String str) {
        String str1 = str.trim();
        if(str1 == null || str1.length() == 0) {
            return 0;
        }
        int fuhao = 1;
        if(str1.charAt(0) == '-') {
            fuhao = -1;
        }
        if(str1.charAt(0) != '+' && str1.charAt(0) != '-') {
            if(str1.charAt(0) < 48 || str1.charAt(0) > 57 ) {
                return 0;
            }
        }
        int len = str1.length();
        long sum = 0;
        if(str1.charAt(0) >= 48 && str1.charAt(0) <= 57) {
            for(int i = 0; i < len; ++i) {
                if(str1.charAt(i) >= 48 && str1.charAt(i) <= 57) {
                    sum = sum * 10 + (str1.charAt(i) - '0');
                    long temp = sum * fuhao;
                    if(temp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
                    if(temp < Integer.MIN_VALUE) return Integer.MIN_VALUE;
                }else {
                    break;
                }
            }
        }else {
            for(int i = 1; i < len; ++i) {
                if(str1.charAt(i) >= 48 && str1.charAt(i) <= 57) {
                    sum = sum * 10 + (str1.charAt(i) - '0');
                    long temp = sum * fuhao;
                    if(temp > Integer.MAX_VALUE) return Integer.MAX_VALUE;
                    if(temp < Integer.MIN_VALUE) return Integer.MIN_VALUE;
                }else {
                    break;
                }
            }
        }
        sum = sum * fuhao;
        return (int)sum;
    }
}
